package com.atguigu.ssyx.acl.service.impl;

import com.atguigu.ssyx.acl.mapper.RoleMapper;
import com.atguigu.ssyx.acl.service.AdminRoleService;
import com.atguigu.ssyx.model.acl.AdminRole;
import com.atguigu.ssyx.model.acl.Role;
import com.atguigu.ssyx.acl.service.RoleService;
import com.atguigu.ssyx.vo.acl.RoleQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jodd.util.StringUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ZhangYK
 * @version 8.0
 * @title RoleServiceImpl
 * @description
 * @create 2024/7/5 18:07
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Resource
    private AdminRoleService adminRoleService;

    @Override
    public IPage<Role> selectRolePage(Page<Role> pageParam, RoleQueryVo roleQueryVo) {
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        if (!StringUtil.isEmpty(roleQueryVo.getRoleName())){
            wrapper.like(Role::getRoleName, roleQueryVo.getRoleName());
        }
        Page<Role> rolePage = baseMapper.selectPage(pageParam, wrapper);
        return rolePage;
    }

    /**
     * 根据用户id获取角色数据
     * @param adminId
     * @return
     */
    @Override
    public Map<String, Object> findRoleByUserId(Integer adminId) {
        Map<String, Object> result = new HashMap<>();
        //查询所有角色
        List<Role> allRolesList = list();
        result.put("allRolesList", allRolesList);
        //拥有角色的id
        List<Role> assignRoles = adminRoleService.lambdaQuery()
                .eq(AdminRole::getAdminId, adminId)
                .list().stream().map(adminRole -> {
                    Role role = lambdaQuery().eq(Role::getId, adminRole.getId())
                            .one();
                    return role;
                }).collect(Collectors.toList());
        result.put("assignRoles", assignRoles);
        return result;
    }

    /**
     * 根据用户分配角色
     * @param adminId
     * @param roleId
     */
    @Override
    public void saveUserRoleRelationShip(Long adminId, Long[] roleId) {
        //删除用户分配角色数据
        adminRoleService.lambdaUpdate()
                .eq(AdminRole::getAdminId,adminId)
                .remove();
        //分配新角色
        List<AdminRole> list = new ArrayList<>();
        for (Long roleId1 : roleId) {
            AdminRole adminRole = new AdminRole();
            adminRole.setRoleId(roleId1);
            adminRole.setAdminId(adminId);
            list.add(adminRole);
        }
        adminRoleService.saveBatch(list);
    }
}
